#include "main.h"

//LED
uchar led_code;

//SEG
uchar seg_pos;
uchar seg_str[12];
uchar seg_buf[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
uchar seg_mode;

//KEY
uchar key_old;

//TIMER
ulong timer_count;

//DS18B20
float temp;

//ADC
bit ctrl_mode; //输出控制：0温控 1光控
uchar adc_val; //光照参数量
uchar adc_out; //输出电压量


//===========ADC=============
void adc_proc() {
	float adc_temp;
	if(timer_count%100) return;
	
	//模式一
	if(~ctrl_mode) { 
		//采集温度
		temp = DS18B20_readTemp() / 16.0;
		
		if(temp <= 10.0)
			adc_temp = 1.0;
		else if(temp >= 40.0)
			adc_temp = 5.0;
		else
			adc_temp = (2.0/15)*temp-(1.0/3);
	} 
	//模式二
	else { 
		//采集光照值
		adc_val = ADC_read(1);
		
		if(adc_val <= 10)
			adc_temp = 1.0;
		else if(adc_val >= 240)
			adc_temp = 5.0;
		else 
			adc_temp = (2.0/115)*adc_val+(19.0/23);
	}
	
	adc_out = (uchar)(adc_temp/(5.0/255));
	ADC_output(adc_out);
}


//===========LED=============
void led_proc() {
	if(timer_count%50) return;
	led_code = (~ctrl_mode) ? 0x01 : 0x02;
}

//===========SEG=============
void seg_proc() {
	if(timer_count%50) return;
	
	switch(seg_mode) {
		case 0:
			if(~ctrl_mode)
				sprintf(seg_str, "1    %3.1f", temp);
			else
				sprintf(seg_str, "2    %3d", (uint)adc_val);
		break;
		case 1:
			sprintf(seg_str, "U     %2.1f", adc_out*(5.0/255));
		break;
	}
	
	seg_tran(seg_str, seg_buf);
}

//===========KEY=============
void key_proc() {
	uchar key_val,key_down;
	if(timer_count%10) return;
	
	//读取键码
	key_val = key_scan_kbd();
	key_down = key_val & (key_old^key_val);
	key_old = key_val;
	
	//按键选择
	if(key_down == 5) {
		if(++seg_mode == 2)
			seg_mode = 0;
	}
	//模式切换
	if(key_down == 4 && seg_mode == 0) {
		ctrl_mode ^= 1;
	}

}

//===========ISR=============
void timer1_init() {
	AUXR &= 0xBF;
	TMOD &= 0x0F;
	TH1 = 0xFC;  //1ms
	TL1 = 0x18;
	TF1 = 0;
	ET1 = 1;
	TR1 = 1;
	EA = 1;
}

void isr_timer_1() interrupt 3 {
	timer_count++;
	
	seg_disp(seg_pos, seg_buf);
	led_disp(led_code);
	if(++seg_pos == 8) seg_pos = 0;
}

//===========MAIN=============
void main() {
	sys_init();
	timer1_init();
	
	while(1) {
		adc_proc();
		led_proc();
		seg_proc();
		key_proc();
	}
}


